<script setup lang="ts">
import {computed, nextTick, onMounted, reactive, ref} from "vue";
import { tableBorder } from "@/utils/border/table-border.ts";
import { Message, PaginationProps } from "@arco-design/web-vue";
import {
  back,
  downPdf, exportSummaryXls,
  exportXls,
  getRegistrationList,
  gotoRoundo,
} from "@/services/newsApi";
import RegistrationForm from "./registrationForm.vue";
import {
  getDictByParentCode,
  listNormalRacetrack,
  listRacetrack,
} from "@/services/commonApi.ts";
import type {
  ListRacetrackType,
  OtherChildrenListType,
} from "@/types/commonType.ts";
import { downloadFile, getRoleCode, getUser } from "@/utils";
import useModal from "@/hooks/useModal.ts";
import RegistrationOrgin from "./registrationOrgin.vue";
import AchieveModal from "@/pages/review/achievement/AchieveModal.vue";
import type {achievementType} from "@/types/achievement.ts";

const colProps = {
  xs: 24,
  sm: 24,
  md: 12,
  lg: 8,
  xl: 8,
  xxl: 8,
};

const achieveRef = ref<{
  init: (data: any) => void
}>()


const data = ref([]);

const { ModalShow, ModalHide } = useModal();

const pagination = reactive<PaginationProps>({
  total: 0,
  current: 1,
  showTotal: true,
  pageSize: 10,
});

const formSearch = reactive({
  current: 1,
  size: 10,
  phone: "",
  projectType: "0",
  projectSource: "",
  channel: "",
  dataDirection: "",
  projectName: "",
  step: "",
  status: "",
});

const helpform = ref<{
  show: () => void;
}>();

const orginform = ref<{
  show: () => void;
}>();

const options = reactive<{
  参赛项目来源: OtherChildrenListType[];
  赛道: ListRacetrackType[];
  企业赛道: ListRacetrackType[];
  loading: boolean;
  export: boolean;
  roundo: boolean
}>({
  参赛项目来源: [],
  赛道: [],
  企业赛道: [],
  loading: false,
  export: false,
  roundo: false
});
// handleExportRoundo

function queryData() {
  // data.value = [];
  options.loading = true;
  getRegistrationList(formSearch)
    .then((res) => {
      if (res.code === 200) {
        data.value = res.data.records;
        pagination.total = res.data.total;
        pagination.current = res.data.current;
        pagination.pageSize = res.data.size;
      } else {
        data.value = [];
        Message.error(res.msg);
      }
    })
    .finally(() => {
      options.loading = false;
    });
}

const handlePageChange = (page: number) => {
  formSearch.current = page;
  queryData();
};

const optionsList = () => {
  getDictByParentCode({
    dictCode: "参赛项目来源",
  })
    .then((res) => {
      if (res.code === 200) {
        options["参赛项目来源"] = res.data[0].children;
        // itemText
        const find = options["参赛项目来源"].find(
          (item) => item.itemText === getUser().username
        );
        if (find) {
          formSearch.projectSource = find.id;
          options["参赛项目来源"] = [find];
        } else {
          formSearch.projectSource = "";
        }
      }
    })
    .finally(() => {
      listRacetrack()
        .then((res) => {
          if (res.code === 200) {
            options["企业赛道"] = res.data;
          }
        })
        .finally(() => {
          listNormalRacetrack()
            .then((res) => {
              if (res.code === 200) {
                options["赛道"] = res.data;
              }
            })
            .finally(() => {
              queryData();
            });
        });
    });
};

onMounted(() => {
  optionsList();
});
// getUser().username === 'admin'

const columns = computed(() => {
  const c = [
    {
      title: "序号",
      dataIndex: "index",
      width: 80,
      slotName: "index",
    },
    {
      title: "报名用户手机号",
      dataIndex: "phone",
      width: 135,
    },
    {
      title: "项目名称",
      dataIndex: "projectName",
      width: 135,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: "参赛项目来源",
      dataIndex: "projectSource",
      width: 100,
    },
    {
      title: "赛题类型",
      dataIndex: "projectType",
      width: 90,
      slotName: "projectType",
    },
    {
      title: "赛道/赛题",
      dataIndex: "channel",
      width: 210,
      slotName: "channel",
    },
    {
      title: "参赛项目基本信息",
      dataIndex: "basicInfoIsOver",
      slotName: "basicInfoIsOver",
      width: 120,
    },
    {
      title: "参赛单位基本信息",
      dataIndex: "orgInfoIsOver",
      slotName: "orgInfoIsOver",
      width: 120,
    },
    {
      title: "团队信息",
      dataIndex: "teamInfoIsOver",
      slotName: "teamInfoIsOver",
      width: 180,
    },
    {
      title: "项目申报书",
      dataIndex: "projectApplicationIsOver",
      slotName: "projectApplicationIsOver",
      width: 95,
    },
    {
      title: "附件",
      dataIndex: "attachmentUploadIsOver",
      slotName: "attachmentUploadIsOver",
      width: 80,
    },
    {
      title: "状态",
      dataIndex: "status",
      slotName: "status",
      width: 80,
    },
    {
      title: "赛程",
      dataIndex: "stepStatus",
      slotName: "stepStatus",
      width: 80,
    },
    {
      title: "操作",
      dataIndex: "action",
      slotName: "action",
      width: 250,
    },
  ];
  // const role = getRoleCode();
  // if (role !== "city_user") {
  //   return [].concat(c, [
  //     {
  //       title: "操作",
  //       dataIndex: "action",
  //       slotName: "action",
  //       width: 250,
  //     },
  //   ]);
  // }
  return c;
});

const registUid = ref("");
const handleInfoClick = (type, record) => {
  registUid.value = record.registUid;
  nextTick(() => {
    switch (type) {
      case "basicInfo":
        break;
      case "orgInfo":
        orginform.value?.show();
        break;
      case "teamInfo":
        break;
      case "projectApplication":
        helpform.value?.show();
        break;
      case "attachment":
        break;
      default:
        return;
    }
  })
};

const handleSearch = () => {
  formSearch.current = 1;
  queryData();
};

const handleReset = () => {
  formSearch.current = 1;
  formSearch.size = 10;
  formSearch.phone = "";
  formSearch.projectType = "0";
  formSearch.projectSource = "";
  formSearch.channel = "";
  formSearch.dataDirection = "";
  formSearch.projectName = "";
  formSearch.step = ""
  formSearch.status = ""
  racetrackList.value = [];
  queryData();
};

const handleExport = () => {
  options.export = true;
  exportXls(formSearch)
    .then((res) => {
      let name = ''
      if (formSearch.step === "") {
        name = "报名项目"
      }
      if (formSearch.step === '1') {
        name = "初赛项目"
      }
      if (formSearch.step === '2') {
        name = "决赛项目"
      }
      if (formSearch.step === '3') {
        name = "淘汰项目"
      }
      downloadFile(res, `${name}.xlsx`);
    })
    .finally(() => {
      options.export = false;
    });
};


const handleSelectChange = () => {
  formSearch.channel = "";
};

const handleTableCancel = (row: any) => {
  ModalShow({
    content: "请确认是否退回当前报名信息？",
  }).then(() => {
    back({
      id: row.registUid,
    })
      .then((res) => {
        if (res.code === 200) {
          Message.success("报名信息已退回");
        }
      })
      .finally(() => {
        ModalHide();
        queryData();
      });
  });
};

const handleTableDownload = (row: any) => {
  downPdf(row.registUid).then((res) => {
    downloadFile(
      res,
      `${row.channel}_${row.projectName}.zip`
    );
  });
};

// 初赛
const handleGoToRoundo = (row: any, step: "1" | "2" | "3") => {
  let str = ""
  if (step === "1") {
    str = "进入初赛"
  }
  if (step === "2") {
    str = "进入决赛"
  }
  if (step === "3") {
    str = "淘汰"
  }
  ModalShow({
    title: "提示",
    content: `请确认当前项目是否${str}？`,
  }).then(() => {
    gotoRoundo({
      id: row.registUid,
      step: step,
    }).then((res) => {
      if (res.code === 200) {
        Message.success(res.msg);
        queryData();
      }
    }).finally(ModalHide)
  })
};


const racetrackList = ref([]);

const handleChangeChannel = (e) => {
  formSearch.dataDirection = "";
  racetrackList.value = [];
  if (formSearch.projectType === "0") {
    const find = options["赛道"].find((item) => item.id === e);
    getDictByParentCode({
      dictCode: find.dictCode,
    }).then((res) => {
      if (res.code === 200) {
        racetrackList.value = res.data[0].children;
      }
    });
  } else if (formSearch.projectType === "1") {
    const find = options["企业赛道"].find((item) => item.id === e);
    getDictByParentCode({
      dictCode: find.dictCode,
    }).then((res) => {
      if (res.code === 200) {
        racetrackList.value = res.data[0].children;
      }
    });
  }
};

const handleINfoTable = (row) => {
  if (row.projectType === "常规赛题") {
    row.projectType = '0'
  }
  if (row.projectType === "企业需求子赛题") {
    row.projectType = '1'
  }

  achieveRef.value?.init({
    registUid: row.registUid,
    projectType: row.projectType
  })
}
</script>

<template>
  <a-space
    class="container"
    direction="vertical"
  >
    <a-card>
      <a-form auto-label-width>
        <a-row :gutter="24">
          <a-col v-bind="colProps">
            <a-form-item label="项目名称">
              <a-input
                  v-model="formSearch.projectName"
                  placeholder="请输入项目名称"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="手机号">
              <a-input
                v-model="formSearch.phone"
                placeholder="请输入手机号"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="参赛项目来源">
              <a-select
                v-model="formSearch.projectSource"
                placeholder="请选择参赛项目来源"
              >
                <a-option
                  v-for="item in options['参赛项目来源']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.itemText }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="赛题类型">
              <a-select
                v-model="formSearch.projectType"
                @change="handleSelectChange"
                placeholder="请选择赛题类型"
              >
                <a-option value="0">常规赛题</a-option>
                <a-option value="1">企业需求子赛题</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="赛道">
              <a-select
                v-model="formSearch.channel"
                v-if="formSearch.projectType === '0'"
                placeholder="请选择赛道"
                @change="handleChangeChannel"
              >
                <a-option
                  v-for="item in options['赛道']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.dictName }}</a-option>
              </a-select>
              <a-select
                v-model="formSearch.channel"
                v-if="formSearch.projectType === '1'"
                placeholder="请选择赛道"
                @change="handleChangeChannel"
              >
                <a-option
                  v-for="item in options['企业赛道']"
                  :key="item.id"
                  :value="item.id"
                >{{ item.dictName }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col v-bind="colProps">
            <a-form-item label="赛题">
              <a-select
                v-model="formSearch.dataDirection"
                placeholder="请选择赛题"
              >
                <a-option
                  v-for="item in racetrackList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.itemText }}</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="赛程">
              <a-select
                  v-model="formSearch.step"
                  placeholder="请选择赛程"
              >
                <a-option value="1">初赛项目</a-option>
                <a-option value="2">决赛项目</a-option>
                <a-option value="3">淘汰项目</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item label="状态">
              <a-select
                  v-model="formSearch.status"
                  placeholder="请选择状态"
              >
                <a-option value="">全部</a-option>
                <a-option value="0">未提交</a-option>
                <a-option value="1">已提交</a-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col v-bind="colProps">
            <a-form-item :label-col-props="{span: 1}">
              <a-space>
                <a-button
                    type="primary"
                    @click="handleSearch"
                >
                  <template #icon>
                    <icon-search />
                  </template>
                  <span>查询</span>
                </a-button>
                <a-button @click="handleReset">
                  <template #icon>
                    <icon-refresh />
                  </template>
                  <span>重置</span>
                </a-button>

                <a-button
                    v-has="'registrationCenter:send:export'"
                    type="primary"
                    status="success"
                    @click="handleExport"
                    :loading="options.export"
                >
                  <template #icon>
                    <icon-export />
                  </template>
                  <span>导出</span>
                </a-button>

              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card>
      <a-table
        :data="data"
        :columns="columns"
        :bordered="tableBorder"
        :pagination="pagination"
        @page-change="handlePageChange"
        column-resizable="false"
        :loading="options.loading"
      >
        <template #index="{rowIndex}">
          {{ (pagination.current - 1) * pagination.pageSize + rowIndex + 1 }}
        </template>

        <template #projectType="{record}">
          <a-tag
            v-if="record.projectType == '常规赛题'"
            bordered
            color="green"
          >常规</a-tag>
          <a-tag
            v-else-if="record.projectType == '企业需求子赛题'"
            color="orangered"
            bordered
          >企业</a-tag>
        </template>

        <template #channel="{record}">
          <div style="display: flex;flex-direction: column;">
            <span style="color: green;">{{ record.channel }}</span>
            <span style="color: orangered;">{{ record.dataDirection }}</span>
          </div>
        </template>

        <template #basicInfoIsOver="{record}">
          <a-tag
            v-if="record.basicInfoIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>

        <template #orgInfoIsOver="{record}">
<!--          <a-link
            :style="{ textDecoration: 'underline' }"
            @click="handleInfoClick('orgInfo', record)"
            :status="record.orgInfoIsOver ? 'success' : 'danger'"
          >
            {{ record.orgInfoIsOver ? '已完成' : '未完成' }}
          </a-link>-->
          <a-tag
              v-if="record.orgInfoIsOver"
              bordered
              color="green"
          >已完成</a-tag>
          <a-tag
              v-else
              bordered
              color="orangered"
          >未完成</a-tag>
        </template>

        <template #teamInfoIsOver="{record}">
          <a-tag
            v-if="record.teamInfoIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>

        <template #projectApplicationIsOver="{record}">
<!--          <a-link
            :style="{ textDecoration: 'underline' }"
            @click="handleInfoClick('projectApplication', record)"
            :status="record.projectApplicationIsOver ? 'success' : 'danger'"
          >
            {{ record.projectApplicationIsOver ? '已完成' : '未完成' }}
          </a-link>-->
          <a-tag
              v-if="record.projectApplicationIsOver"
              bordered
              color="green"
          >已完成</a-tag>
          <a-tag
              v-else
              bordered
              color="orangered"
          >未完成</a-tag>
        </template>

        <template #attachmentUploadIsOver="{record}">
          <a-tag
            v-if="record.attachmentUploadIsOver"
            bordered
            color="green"
          >已完成</a-tag>
          <a-tag
            v-else
            bordered
            color="orangered"
          >未完成</a-tag>
        </template>

        <template #status="{record}">
          <a-tag
            bordered
            color="green"
            v-if="record.status === 1"
          >已提交</a-tag>
          <a-tag
            bordered
            color="orangered"
            v-else-if="record.status === 0"
          >未提交</a-tag>

        </template>
        <template #stepStatus="{record}">
          <a-tag
            bordered
            color="arcoblue"
            v-if="record.stepStatus === 2"
          >初赛</a-tag>
          <a-tag
            bordered
            color="magenta"
            v-else-if="record.stepStatus === 3"
          >决赛</a-tag>
          <a-tag
              bordered
              color="gray"
              v-else-if="record.stepStatus === 4"
          >淘汰</a-tag>
        </template>
        <!--        stepStatus-->

        <template #action="{record}">
          <a-button v-if="getRoleCode() === 'city_user'" type="primary" @click="handleINfoTable(record)">详细</a-button>

          <div v-if="getRoleCode() !== 'city_user'">
            <a-space v-if="record.status === 0">
              <a-button type="primary" @click="handleINfoTable(record)">详细</a-button>
              <a-button v-if="record.stepStatus"
                        type="primary"
                        v-has="'registrationCenter:send:download'"
                        @click="handleTableDownload(record)"
              >下载</a-button>

              <a-space v-if="record.stepStatus === 2">
                <a-button
                    status="warning"
                    type="primary"
                    v-has="'registrationCenter:send:final'"
                    @click="handleGoToRoundo(record, '2')"
                >决赛</a-button>
              </a-space>
            </a-space>

            <a-space direction="vertical"  v-else-if="record.status === 1">
              <div>
                <a-space>
                  <a-button type="primary" @click="handleINfoTable(record)">详细</a-button>
                  <a-button
                      type="primary"
                      v-has="'registrationCenter:send:download'"
                      @click="handleTableDownload(record)"
                  >下载</a-button>
                  <a-button
                      status="danger"
                      type="primary"
                      v-has="'registrationCenter:send:back'"
                      @click="handleTableCancel(record)"
                  >退回</a-button>
                </a-space>
              </div>
              <div v-if="record.stepStatus !== 3">
                <a-space v-if="record.stepStatus !== 4">
                  <a-button
                      status="success"
                      v-if="record.stepStatus != 2 && record.stepStatus != 3"
                      type="primary"
                      v-has="'registrationCenter:send:final'"
                      @click="handleGoToRoundo(record, '1')"
                  >初赛</a-button>
                  <a-button
                      @click="handleGoToRoundo(record, '3')"
                      v-if="record.stepStatus != 2 && record.stepStatus != 3"
                      class="out"
                  >淘汰</a-button>
                  <a-button
                      v-if="record.stepStatus === 2"
                      status="warning"
                      type="primary"
                      v-has="'registrationCenter:send:final'"
                      @click="handleGoToRoundo(record, '2')"
                  >决赛</a-button>
                </a-space>
              </div>
            </a-space>
          </div>
        </template>
      </a-table>
    </a-card>
  </a-space>

  <registration-form
    ref="helpform"
    @list="queryData"
    :registUid="registUid"
  />

  <registration-orgin
    ref="orginform"
    @list="queryData"
    :registUid="registUid"
  />
  <AchieveModal ref="achieveRef"></AchieveModal>
</template>

<style scoped lang="scss">
.title {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}
:deep(.arco-btn-secondary) {
  &.out {
    background: #ccc !important;
  }
}
</style>